package com.ruoyi.web.controller.system;

import com.ruoyi.system.domain.Franchiser;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Helper {
    // 8-16位，只允许数字和字母，需同时包含数字和字母
    public static boolean isValidPassword(String password) {
        String regex = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,16}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(password);
        return matcher.matches();
    }

    public static Franchiser findFranchiser(List<Franchiser> franchiserList, long franchiserId) {
        for (Franchiser franchiser : franchiserList) {
            if (franchiser.getFranchiserId() == franchiserId) {
                return franchiser;
            }
        }
        return null;
    }

    public static String getLogLockKey(long logId) {
        return String.format("sa_lock_log_%d", logId);
    }

    public static String getProxyRecordLockKey(long id) {
        return String.format("sa_lock_proxy_record_%d", id);
    }

    public static String getLastOrderIdKey() {
        return "sap2_last_orderId_1006";
    }

    public static String getDealConsumeUnionLockKey() {
        return "sap2_consume_union_lock_key";
    }

    public static String getConsumeLogKey(long account) {
        return "sap2_consume_union_log:" + account;
    }

    public static String getConsumeLogRunningKey(long account) {
        return "sap2_consume_union_log_running:" + account;
    }

    public static String getConsumeTodoKey() {
        return "sap2_consume_todo";
    }

    public static long getConsumePeriodTimeEnd() {
        final long period = 3600 * 3;
        final long timePeriodStart = 1743436800;
        long timestamp = System.currentTimeMillis() / 1000L;
        long n = (timestamp - timePeriodStart) / period;
        // 上个周期的时间
        long timeEnd = n * period + timePeriodStart;
        return timeEnd;
    }

    public static long getUTCTimestamp(String strDate, String strFormat) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(strFormat);
        // 将字符串解析为 LocalDateTime 对象
        LocalDateTime localDateTime = LocalDateTime.parse(strDate, formatter);
        // 转换为时间戳（毫秒）
        long timestamp = localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        return timestamp / 1000L;
    }
}
